package obj;

import data.DataHelper;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Body {

    public static final String BODIES_PATH = "data/body/body.%s.txt";
    public static final String BASE_URL = "http://extramobi.ru/product/korpus_";

    public String model;
    public String brandName;
    public int price;
    public int oldPrice;
    public int count;
    public String url;

    public static Body parseBody(String line, double coef) {
        Body body = new Body();
        String[] fields = line.split(";");
        String brand = fields[0].split("\\s")[0];
        if (brand.equals("Sony")) {
            brand = "Sony Ericsson";
        }
        body.brandName = brand;
        body.model = fields[0];
        if (fields.length == 4) {
            body.price = Integer.parseInt(fields[1]);
            body.oldPrice = Integer.parseInt(fields[2]);
            body.count = Integer.parseInt(fields[3].trim());
        } else {
            body.price = Integer.parseInt(fields[1]);
            body.count = Integer.parseInt(fields[2].trim());
            body.oldPrice = (int) (body.price * coef);
        }
        body.url = DataHelper.codeInURL(BASE_URL + body.model);
        return body;
    }

    public static List<Body> parseBodies(String brandName, double coef) throws IOException {
        List<Body> bodies = new ArrayList<Body>();
        BufferedReader reader = new BufferedReader(new FileReader(String.format(BODIES_PATH, brandName.replace("Sony Ericsson", "se"))));
        String line;
        while ((line = reader.readLine()) != null) {
            Body body = Body.parseBody(line, coef);
            bodies.add(body);
        }
        return bodies;
    }

}
